<template>
  <div>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      status-icon
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
    >
      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title" autocomplete="off" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <Editor @change="changeEditor" />
      </el-form-item>
      <el-form-item label="类别" prop="category">
        <el-select v-model="ruleForm.category">
          <el-option
            v-for="item in categoryOption"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="封面图片" prop="coverPicture">
        <Upload :avatar="ruleForm.coverPicture" @change="handleChange" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)"
          >添加新闻</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import uploadFun from '@/util/uploadFun';
import Upload from '@/components/upload/Upload.vue';
import Editor from '@/components/editor/Editor.vue';
import { useRouter } from 'vue-router';
const router=useRouter();
const ruleFormRef = ref();
const ruleForm = reactive({
  category: 1,
  title: '',
  content: '',
  coverPicture: '',
  file: null,
  isPublish: 0, //0未发布，1发布
});
const categoryOption = [
  { value: 1, label: '最新动态' },
  { value: 2, label: '典型案例' },
  { value: 3, label: '通知公告' },
];
const rules = reactive({
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  category: [{ required: true, message: '请选择类别', trigger: 'blur' }],
  coverPicture: [
    { required: true, message: '请选择封面图片', trigger: 'change' },
  ],
});
const handleChange = (file) => {
  ruleForm.coverPicture = URL.createObjectURL(file);
  ruleForm.file = file;
};
const changeEditor = (val) => {
  ruleForm.content = val.getHtml();
};
const submitForm = () => {
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      const res = await uploadFun('/adminApi/news/add', ruleForm);
      if (res.code === 200) {
        ElMessage({
          message: res.msg,
          type: 'success',
        });
        router.push('/news-manage/news-list');
      }
    }
  });
};
</script>
<style lang="scss"></style>
